import { isNavigationFailure, Router } from 'vue-router';
import { useUserStore } from '@/pinia/modules/user';

const defaultRoutePath = '/';

// 用户登录白名单 路由 name[]
const APP_WHITE_LIST = ['Login'];

export default function routerGuards(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const callback = () => {
      if (to.name === 'Login') {
        next({ path: defaultRoutePath });
      } else {
        const hasRoute = router.hasRoute(to.name!);
        if (!hasRoute) {
          next({ name: 'NotFound' });
        } else {
          next();
        }
      }
    };

    const token = userStore.token;
    try {
      if (token) {
        if (!userStore.hasUserInfo) {
          const hasInfo = await userStore.getUserDetail();
          // 如果成功获取用户信息
          if (hasInfo) {
            callback();
          } else {
            // 没有用户信息，跳转到登录
            next({
              path: '/login',
              // query: { redirect: to.name === 'Register' ? '/' : to.fullPath },
              replace: true,
            });
          }
        } else {
          callback();
        }
      } else {
        if (APP_WHITE_LIST.includes(to.name as string)) {
          // 在免登录名单，直接进入
          next();
          return;
        }
        next({
          path: '/login',
          // query: { redirect: to.fullPath },
          replace: true,
        });
      }
    } catch (error) {
      if (to.name === 'NotFound') {
        next();
      } else {
        next({ name: 'NotFound' });
      }
    }
  });

  router.afterEach((to, from, failure) => {
    if (to?.meta?.title) {
      document.title = to.meta.title + ``;
    }
    if (isNavigationFailure(failure)) {
      console.log('vue-router 导航出错', failure);
    }
  });

  router.onError(error => {
    console.log(error, '路由错误');
  });
}
